﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Common;

namespace WebSite.Core
{
    public class LoginHelper
    {
        public static void SetCurrentUser( string username, bool red= true )
        {
            Maticsoft.BLL.CarrefourCover.Account bll = new Maticsoft.BLL.CarrefourCover.Account();
            var queryResult = bll.GetModelList( "username='" + username.SqlFilter() + "'" );

            int uid = 0;

            if (queryResult.Count == 0)
            {
                uid = bll.Add( new Maticsoft.Model.CarrefourCover.Account()
                {
                    UserName = username,
                    Passwrod = "",
                    Ip = HttpContext.Current.Request.UserHostAddress,
                    CreateTime = DateTime.Now,
                    TelePhone = ""
                } );
            }
            else
            {
                uid = queryResult[0].Id;
            }

            Project_Session.SetSession( uid, username );

            if (red)
            {
                HttpContext.Current.Response.Redirect("/Index.aspx");
            }
        }

        public static void SetCurrentUser( string username, string password, bool redirect = true )
        {
            BasePage page = HttpContext.Current.Handler as BasePage;
            if (page == null)
            {
                return;
            }

            if (string.IsNullOrEmpty( username ) || string.IsNullOrEmpty( password ))
            {
                page.AlertMessageBack( "请填写用户名和密码" );
            }

            var bll = new Maticsoft.BLL.CarrefourCover.Account();
            var entity = bll.GetModelList( "UserName='" + username.SqlFilter() + "' AND Passwrod = '" + password.SqlFilter() + "'" );

            if (entity.Count == 0)
            {
                page.AlertMessageBack( "用户名或密码错误" );
            }
            else
            {
                Project_Session.SetSession( entity[0].Id, entity[0].UserName );
                
                if (redirect)
                {
                    if (string.IsNullOrEmpty( page.Request["ReturnUrl"] ))
                    {
                        page.Response.Redirect( "/Index.aspx" );
                    }
                    else
                    {
                        page.Response.Redirect( page.Request["ReturnUrl"] );
                    }
                }
            }
        }

        
    }
}